package com.suda.sudaexamsystem.controller;

import com.suda.sudaexamsystem.pojo.User;
import com.suda.sudaexamsystem.service.UserService;
import com.suda.sudaexamsystem.util.AjaxResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 用于测试登录页面
 */
@Controller
@RequestMapping("/users")
@Slf4j
public class UserHtmlController {
    @Autowired
    private UserService userService;

    // 去登录页面
    @GetMapping("/login")
    public String toLogin() {
        // 默认是访问templates目录下   完整路径templates/user/loginTest.html
        return "user/login";
    }

    // 去注册界面
    @GetMapping("/register")
    public String toRegister() {
        return "user/register";
    }

    // 返回页面的方法
    @PostMapping(value = "/log_in")
    public String login(String name, String password, HttpServletRequest request) {
        User user = userService.findByNameAndPassword(name, password);
        log.info("name：" + name + ", password：" + password);
        if (user == null) {
            return "user/login";
        }
        request.getSession().setAttribute("user", user);
        // 返回的页面  登录后的主页
        return "examIndex";
    }

    // 注册后返回登录页面
    @PostMapping(value = "/toRegister")
    public String registerUser(User user) {
        userService.registerUser(user);
        return "user/login";
    }

    // 退出登录
    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("user", null);
        session.invalidate();
        return "/user/login";
    }
}
